import { _decorator, Component, Node, Label, tween, view, UITransform, Button, ScrollView, Prefab, instantiate, find, color, LabelOutline } from 'cc';
import { App } from '../App';
import { EventConst } from '../common/Common';
import CommConst from '../const/CommConst';
import wsTool from '../net/ws';
import { PD } from '../player/PlayerData';
import UtilTool from '../tools/UtilTool';
import ScrollHelper from './ScrollHelper';
import { WalletSwapPanel } from './WalletSwapPanel';
const { ccclass, property } = _decorator;

// 钱包界面
@ccclass('WalletPanel')
export class WalletPanel extends Component {
    @property(Node)
    contentNode: Node = null;

    @property(Prefab)
    WalletSwapPrefab: Node = null;

    @property(Node)
    bottomNode: Node = null;

    @property(Node)
    scrollNode_cz: Node = null;

    @property(Node)
    scrollNode_tx: Node = null;

    @property(Node)
    myCoin: Node = null;

    @property(Node)
    emptyNode_cz: Node = null;

    @property(Node)
    emptyNode_tx: Node = null;


    private selIndex = 0 // [0]我的购买 [1]我的兑换
    private itemNum = 5
    // [listData]购买列表数据  [isLoading]是否加载中 [loadOver]是否加载结束(如果没有新的数据则认为是加载结束) [currPage]当前已经请求的第几页的数据 [dataDirty]是否需要重新拉取数据 [pageSize]每页请求的数量
    private cz_configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}

    // [listData]兑换列表数据  [isLoading]是否加载中 [loadOver]是否加载结束(如果没有新的数据则认为是加载结束) [currPage]当前已经请求的第几页的数据 [dataDirty]是否需要重新拉取数据 [pageSize]每页请求的数量
    private tx_configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}

    onLoad() {
        App.Event.on(EventConst.UPDATE_COIN,this.setCoin, this )

        App.Event.on(EventConst.UPDATE_WITHDRAW_JL,(data)=>{
            UtilTool.printLog('主动推送更新兑换记录信息',data)
            this.updateWithdrawLJ(data)
        },this)
    }

    start() {
        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())
        UtilTool.setScreen(this.node)
        this.emptyNode_cz.active = false
        this.emptyNode_tx.active = false

        // 适配
        UtilTool.setSize(this.bottomNode, 3, [0, 2])
        UtilTool.setSize(this.scrollNode_cz, 3, [0, 2])
        UtilTool.setSize(this.scrollNode_cz.getChildByName("view"), 3, [0, 2])
        UtilTool.setSize(this.scrollNode_cz.getChildByName("view").getChildByName("content"), 3, [0, 2])

        UtilTool.setSize(this.scrollNode_tx, 3, [0, 2])
        UtilTool.setSize(this.scrollNode_tx.getChildByName("view"), 3, [0, 2])
        UtilTool.setSize(this.scrollNode_tx.getChildByName("view").getChildByName("content"), 3, [0, 2])
        UtilTool.setPos(this.bottomNode, [0, 1])

        UtilTool.setPos(this.emptyNode_cz, [0, 1], true)
        UtilTool.setPos(this.emptyNode_tx, [0, 1], true)

        for (let index = 0; index < 2; index++) {
            var btn =  this.bottomNode.getChildByName("btn_toggle"+index)
            App.onClick.addButtonClickEvent(btn.getComponent(Button), async() =>{
                this.clickBottom(index,false)
            }, this,null,true,null,null,500); 
        }
        this.clickBottom(this.selIndex,true)

        this.setCoin()

        let H = UtilTool.getGapSize().height*2
        if (H>0) {
            this.itemNum = this.itemNum + Math.ceil(H/400)
        }
    }

    // 点击切换按钮
    clickBottom(index, bInit) {
        if (!bInit) {
            if (this.selIndex == index) {
                return 
            }
        }

        this.selIndex = index
        for (var i=0; i<2 ;i++) {
            var btn =  this.bottomNode.getChildByName("btn_toggle"+i)
            btn.getChildByName("spr").active = index==i
            // btn.getChildByName("wz").getComponent(Label).color = index==i?color(255, 164, 49, 255):color(68, 64, 50, 255)
            btn.getChildByName("wz").getComponent(LabelOutline).width = index==i?4:0
        }

        this.scrollNode_cz.active = this.selIndex==0
        this.scrollNode_tx.active = this.selIndex==1

        if (this.selIndex==0) {
            if (this.cz_configData.listData.length<=0) {
                this.reqData_cz()
            }
        }
        else if (this.selIndex==1) {
            if (this.tx_configData.listData.length<=0) {
                this.reqTXData_tx()
            }
        }
    }

    /**
     * 更新金币
     */
    setCoin() {
        var coin = PD.user.coin_str
        this.myCoin.getComponent(Label).string = coin

        UtilTool.adaptiveLabel([this.myCoin,find("top/spr",this.contentNode)], 0, 10)
    }

    /**
     * 购买
     */
    clickRecharge() {
        App.Audio.playOneShot("click")
        let panel = instantiate(this.WalletSwapPrefab)
        this.node.addChild(panel)

        panel.getComponent(WalletSwapPanel).showView(this,0)
    }

    /**
     * 兑换
     */
    clickWithdraw() {
        App.Audio.playOneShot("click")
        let panel = instantiate(this.WalletSwapPrefab)
        this.node.addChild(panel)

        panel.getComponent(WalletSwapPanel).showView(this,1)

    }

    /**
     * 重置数据
     * param isAll 是否重置所有数据
     * param index 重置索引
     */
    resetReqdata(isAll=true, index=0) {
        if (isAll) {
            this.cz_configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}
            this.tx_configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}
            this.scrollNode_cz.getComponent(ScrollView).content.removeAllChildren()
            this.scrollNode_tx.getComponent(ScrollView).content.removeAllChildren()
            this.emptyNode_cz.active = false
            this.emptyNode_tx.active = false
            this.selIndex = 0
        }
        else {
            if (index==0) {
                this.cz_configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}
                this.scrollNode_cz.getComponent(ScrollView).content.removeAllChildren()
                this.emptyNode_cz.active = false
            }
            else if (index==1) {
                this.tx_configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}
                this.scrollNode_tx.getComponent(ScrollView).content.removeAllChildren()
                this.emptyNode_tx.active = false
            }
        }

        if (this.selIndex == index) {
            this.clickBottom(this.selIndex,true)
        }
        
    }

    ////////////////////////////////////////////////////////////  我的购买记录 ////////////////////////////////////////////////////////////
    /**
     * 请求购买记录数据
     */
    reqData_cz(pInit=true) {
        this.cz_configData.isLoading = true
        wsTool.send({"msgCode":CommConst.Req_BUY_RECORD, "page":this.cz_configData.currPage, "pageSize":this.cz_configData.pageSize})
        .then(res =>{
            // if (res?.result == 0) {
                // 数据回来
                this.cz_configData.currPage = this.cz_configData.currPage + 1
                this.cz_configData.isLoading = false
                // this.cz_configData.listData = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
                res.list.forEach(element => {
                    this.cz_configData.listData.push(element)
                });
                if (res.list==null || res.list.length < this.cz_configData.pageSize) {
                    this.cz_configData.loadOver = true
                }

                this.emptyNode_cz.active = this.cz_configData.listData.length<=0?true:false
                // 最新请求的数据列表大于0，才会去刷新界面
                if (res.list.length>0) {
                    let param = {
                        init:pInit, 
                        data:this.cz_configData.listData, 
                        itemNum:this.itemNum, 
                        itemFun: (obj,idx,objIdx)=>{
                            this.refreshItem_cz(obj,idx,objIdx)
                        },
                        endFun:()=>{
                            this.OnScrollEnd_cz()
                        }
                    }
    
                    this.scrollNode_cz.getComponent(ScrollHelper).setData(param)
                }
                
            // }
            // else{
            //     alert('获取数据失败')
            // } 
        })
    } 

    /** 
     * 刷新数据
     * param obj item对象
     * param idx 实际的下标索引
     * param objIdx item本身的下标索引
    */
    refreshItem_cz(obj,idx,objIdx) {
        if (this.cz_configData.listData.length <= 0) {
            return
        }

        let adress = find("di/adress", obj).getComponent(Label)
        let coin = find("di/coin", obj).getComponent(Label)
        let time = find("di/time", obj).getComponent(Label)
        let state = find("di/state", obj).getComponent(Label)
        let USDT = find("di/USDT", obj).getComponent(Label)
        let itemData = this.cz_configData.listData[idx]

        adress.string = UtilTool.getShortWalletAddr(itemData.account) 
        coin.string = "+" + itemData.value + App.language.getLanguageLab(58)
        time.string = UtilTool.formatTimeStamp(itemData.createTime)
        state.string = itemData.status==1?App.language.getLanguageLab(59):App.language.getLanguageLab(60)
        USDT.string = "-" + itemData.value/PD.gameConfig.chargeScale + " " + PD.user.usdt

        
    }

    // 滚动视图滑到底部回调
    OnScrollEnd_cz() {
        if (this.cz_configData.isLoading) {
            return
        }
        if (this.cz_configData.loadOver) {
            return
        }

        this.reqData_cz(false)
    }

    ////////////////////////////////////////////////////////////  我的购买记录 ////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////  我的兑换记录 ////////////////////////////////////////////////////////////
    /**
     * 请求兑换记录数据
     */
    reqTXData_tx() {
        this.tx_configData.isLoading = true
        wsTool.send({"msgCode":CommConst.Req_TX_RECORD, "page":this.tx_configData.currPage, "pageSize":this.tx_configData.pageSize})
        .then(res =>{
            // if (res?.result == 0) {
                // 数据回来
                this.tx_configData.currPage = this.tx_configData.currPage + 1
                this.tx_configData.isLoading = false
                // this.tx_configData.listData = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
                res.logs.forEach(element => {
                    this.tx_configData.listData.push(element)
                });
                if (res.logs==null || res.logs.length < this.tx_configData.pageSize) {
                    this.tx_configData.loadOver = true
                }

                this.emptyNode_tx.active = this.tx_configData.listData.length<=0?true:false
                // 最新请求的数据列表大于0，才会去刷新界面
                if (res.logs.length>0) {
                    let param = {
                        init:true, 
                        data:this.tx_configData.listData, 
                        itemNum:this.itemNum, 
                        itemFun: (obj,idx,objIdx)=>{
                            this.refreshItem_tx(obj,idx,objIdx)
                        },
                        endFun:()=>{
                            this.OnScrollEnd_tx()
                        }
                    }
    
                    this.scrollNode_tx.getComponent(ScrollHelper).setData(param)
                }
                
            // }
            // else{
            //     alert('获取数据失败')
            // } 
        })
    }

    /** 
     * 刷新数据
     * param obj item对象
     * param idx 实际的下标索引
     * param objIdx item本身的下标索引
    */
    refreshItem_tx(obj,idx,objIdx) {
        if (this.tx_configData.listData.length <= 0) {
            return
        }

        let adress = find("di/adress", obj).getComponent(Label)
        let coin = find("di/coin", obj).getComponent(Label)
        let time = find("di/time", obj).getComponent(Label)
        let state = find("di/state", obj).getComponent(Label)
        let USDT = find("di/USDT", obj).getComponent(Label)
        let itemData = this.tx_configData.listData[idx]

        obj.dataId = itemData.id
        adress.string = UtilTool.getShortWalletAddr(itemData.account) 
        coin.string = "-" + itemData.usdt + App.language.getLanguageLab(58)
        time.string = UtilTool.formatTimeStamp(itemData.createTime)
        state.string = ""
        USDT.string = "+" + itemData.usdt/PD.gameConfig.chargeScale + " " + PD.user.usdt

        // 0:审核中,1已完成,2:未通过
        let lanArr = [App.language.getLanguageLab(66), App.language.getLanguageLab(67), App.language.getLanguageLab(68)]
        if (itemData.status>=0 && itemData.status<=2) {
            state.string = lanArr[itemData.status]
        }
    }

    // 滚动视图滑到底部回调
    OnScrollEnd_tx() {
        if (this.tx_configData.isLoading) {
            return
        }
        if (this.tx_configData.loadOver) {
            return
        }

        this.reqTXData_tx()
    }

    // 更新兑换记录
    updateWithdrawLJ(newData) {
        let idx = null
        // 刷新列表数据
        for (let i = 0; i < this.tx_configData.listData.length; i++) {
            let oneData = this.tx_configData.listData[i]
            if (oneData.id == newData.id) {
                this.tx_configData.listData[i] = newData
                idx = i
                break
            }
        }

        if (idx!=null) {
            // 刷新界面显示
            let itemsList = this.scrollNode_tx.getComponent(ScrollHelper).itemsList
            for (let i = 0; i < itemsList.length; i++) {
                let obj = itemsList[i]
                if (obj.dataId == newData.id) {
                    this.refreshItem_tx(obj, idx, i)
                    break
                }
            }
        }
    }

    /**
     * 关闭
     */
    clickClose() {
        App.Audio.playOneShot("click")
        this.node.destroy()
    }

    onDestroy() {
        App.Event.off(EventConst.UPDATE_COIN,this.setCoin,this)
    }
}

